#include <cstdio>
#include <fcntl.h>
#include <unistd.h>
#include "iservice_registry.h"
#include "usart_proxy.h"
#include <iostream>

using namespace OHOS;
using namespace OHOS::Usart_Standard;

namespace OP
{
enum Opcode{
    OPEN,CLOSE,IS_OPEN,READ,WRITE,READLINE,HELP,EXIT,NO_OP=-1,
} ; 
} // namespace OP
OP::Opcode get_opcode(const std::string& op){
    using namespace OP;
    const static std::map<std::string,OP::Opcode> mp{
        {"open",OPEN },{"close",CLOSE},{"is_open",IS_OPEN},{"read",READ},{"write",WRITE},{"readline",READLINE},
        {"help",HELP},{"exit",EXIT}
    };
    auto it=mp.find(op);
    if(it==mp.end()){
        return NO_OP;
    }
    return it->second;
}


int main() {
    using namespace std;
    auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
    if(samgr ==nullptr){
        fprintf(stderr, "Get samgr failed\n");
        return 0;
    }
    sptr<IRemoteObject> object = samgr->GetSystemAbility(9901);
    if (object == nullptr)
    {
        fprintf(stderr, "Get UsartService failed\n");
        return 0;
    }
    auto proxy = iface_cast<IUsartAbility>(object);
    if (proxy == nullptr)
    {
        fprintf(stderr, "Cast proxy failed\n");
        return 0;
    }
    //真正的端口是 “dev/ttyS7”
    const std::string name = "/dev/ttyS7";
    
    int ret1 = proxy->open(name);
    if (ret1 != 0) {
        fprintf(stderr, "open uart failed\n");
        return 0;
    }

    proxy->begin_read_loop(name);
    fprintf(stderr, "proxy begin reading\n");
    for(int i=0;i<100;++i){
        auto s = proxy->read_from_looper(name);
        fprintf(stderr,"read from loop is: %s\n",s.c_str());
        for(auto c:s){if(c =='!'){break;}}
        sleep(1);
    }
    proxy->end_read_loop(name);
    fprintf(stderr, "proxy end reading\n");
    proxy->close(name);
    fprintf(stderr, "close port %s\n",name.c_str());
    return 0;
}